
package com.vodafone.nowplus.android.peoplemail.singlesignon;

import java.security.Principal;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import android.util.Log;



/**
 * Verifies and validates calling activites that provide X509 certificates
 */
public class IdentityVerifier {

    private Certificate CACertificate;

    private String mCertificateFileName = "Android_People_Client_CA.crt";

    /**
     * Reads the CA Certificate used for verification of signed certificates
     */
    protected IdentityVerifier() {

        try {
            CACertificate = CertificateFactory.getInstance("X.509").generateCertificate(  SSOReceiver.assetManager.open(mCertificateFileName));
        } catch (Exception e) {
            Log.e("IdentityVerifier","Constructor",e);
        }
    }

    /**
     * Extracts the package name for this certificate
     * 
     * @param certificate X509Certificate containing the package name
     * @return String containg the package name
     */
    public String extractPackageName(X509Certificate certificate) {
        Principal principal = certificate.getSubjectDN();
        if (principal != null) {
            String principalName = principal.getName();
            String[] tokens = principalName.split("[=,]");
            return tokens[1].trim();
        }
        return null;
    }

    /**
     * Verifies the identity of a calling activity providing a certificate. The
     * Certificate must be valid, signed with the CA Certificate and contain as
     * package name the name of the calling activity
     * 
     * @param cert X509Certificate used for identification of the calling
     *            activity
     * @param caller package name of the calling activity
     * @return true if the calling activity could be verified, false otherwise
     */
    public boolean verifyIdentity(X509Certificate cert, String caller) {
        try {
            cert.checkValidity();
            cert.verify(CACertificate.getPublicKey());
            if (caller==null || !caller.equals(extractPackageName(cert))){
                return false;
            }
        } catch (Exception e) {
            Log.e("IdentityVerifier","verifyIdentity",e);
            return false;
        }
        return true;
    }

}
